#include "WordReport.h"

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
#include <string>
#include <sstream>

std::shared_ptr<WordReport> WordReport::Create() {
    return std::make_shared<TextReport>();
}

static bool startsWith(const std::string& word, char target) {
    if (word.empty()) {
        return false;
    }

    char firstChar = std::tolower(word[0]);
    char targetLower = std::tolower(target);

    return firstChar == targetLower;
}

static int countWordsStartingWith(const std::vector<std::string>& words, char target) {
    return std::count_if(words.begin(), words.end(), [target](const std::string& word) {
        return startsWith(word, target);
    });
}

void TextReport::Print(const std::vector<std::string>& words){
    Calculate(words);
    std::cout << summarize << std::endl;
}

void TextReport::Calculate(const std::vector<std::string>& words) {
    m_words = words;
    SortWords();
#if 0
    summarize.append("Total number of words: ");
    summarize.append(std::to_string(m_words.size()));
    summarize.append("\n");

    for (char c = 'a'; c <= 'z'; c++)
    {
        int count = countWordsStartingWith(m_words, c);
        if (count > 0)
        {
            summarize.append("The nember of word started with char '");
            //summarize.append(std::to_string(c));
            summarize.push_back(c);
            summarize.append("': ");
            summarize.append(std::to_string(count));
            summarize.append("\n");
        }
    }

    summarize.append("=========================");
    summarize.append("\n");
    //list all words here
    char current = 'a';
    for (const std::string& word : m_words) {
        if(word[0]!= current){
            summarize.append("\n");
        }
        summarize.append(word);
        summarize.append(" ");
        current = word[0];
    }
#else
        std::stringstream ss;

        ss << "Total number of words: " << m_words.size() << "\n";

        for (char c = 'a'; c <= 'z'; c++) {
            int count = countWordsStartingWith(m_words, c);
            if (count > 0) {
                ss << "The number of words started with char '" << c << "': " << count << "\n";
            }
        }
        ss << "=========================\n";

        // 列出所有单词，按首字母分组并换行显示
        char current = 'a';
        for (const std::string& word : m_words) {
            if (word[0]!='a' && word[0]!= current) {
                ss << "\n";
                current = word[0];
            }
            ss << word << " ";
        }

        summarize = ss.str();
#endif
}

std::string TextReport::GetSummary() {
    return summarize;
}

void TextReport::SortWords() {
    std::sort(m_words.begin(), m_words.end(), [](const std::string &s1, const std::string &s2) -> bool
              { return s1[0] < s2[0]; });
}